package com.zzx.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zzx.exception.ExceptionState;
import com.zzx.exception.SystemException;
import com.zzx.service.UploadService;
import com.zzx.util.DateUtils;
import com.zzx.util.ResponseResult;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
@Data
@ConfigurationProperties(prefix = "qiniuyun")
public class UploadServiceImpl implements UploadService {

    private String accessKey;
    private String secretKey;
    private String bucket;
    @Override
    public ResponseResult Upload(MultipartFile file) {
        /*获取上传过来的文件名称*/
        String originalFilename = file.getOriginalFilename();
        String fileName = DateUtils.getFileName(originalFilename);
        String uploading = uploading(file, fileName);
        if(!StringUtils.hasText(uploading)) throw new SystemException(ExceptionState.FAILTOUPLOAD);
        Map map = new HashMap<>();
        map.put("tmp_path",uploading);
        map.put("url","http://rfd1v859w.hn-bkt.clouddn.com/"+uploading);
        //返回文件名称
        return new ResponseResult("上传成功",ExceptionState.OK,map);
    }


    public String uploading(MultipartFile file,String fileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        /*上传管理器*/
        UploadManager uploadManager = new UploadManager(cfg);


        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;


        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            /*获取网络中的流对象*/
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
return null;
    }
}
